<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="img" label="图片">
				<image :src="formData.img" style="width: 500px;height: 410px;" mode="heightFix"></image>
				<button type="primary" @click="$uploadImg(setFormImg)">上传</button>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/banner.js';
	import chooseAndUploadImage from '@/js_sdk/tencentcloud-plugin-cos/choose-and-upload-image.js';
	import getFileAccessUrl from '@/js_sdk/tencentcloud-plugin-cos/get-file-access-url.js';
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'banner';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"img": "",
				"sort": null
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			setFormImg(url) {
				console.log(url)
				this.formData.img = url
			},
			async eventHandler(inser) {
				try {
					const key = await chooseAndUploadImage(); // 返回的key即上传到COS的图片文件名（不包含域名部分，一般用来提交给后台接口保存到数据库）
					const url = this.$cdn + key // 返回的url即前面上传到COS的图片的访问地址（包含临时签名）
					console.log(url)
					this.formData.img = url
					uni.showToast({
						title: "上传成功",
						duration: 1500,
					})
					//inser(url,'aa',url)
				} catch (error) {
					console.log(error);
				}
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field("img,sort").get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
